package com.buddies.lottery.ui.web;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageButton;
import android.widget.ProgressBar;

import com.blankj.utilcode.util.AppUtils;
import com.buddies.lottery.App;
import com.buddies.lottery.R;
import com.buddies.lottery.base.BaseActivity;
import com.buddies.lottery.common.ConfigManager;
import com.r0adkll.slidr.Slidr;
import com.r0adkll.slidr.model.SlidrInterface;
import com.tencent.bugly.crashreport.BuglyLog;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class WebActivity extends BaseActivity {

    private static final String TAG = WebActivity.class.getSimpleName();

    protected WebView mWebView;
    private ProgressBar progressBar;

    protected String link;
    private String title;

    protected ImageButton mShareBtn;
    private boolean isOnPause = false;
    private SlidrInterface mSlidrInterface;
    private boolean mActivityFinishFlag = false;

    // 点击分享按钮，未登录的情况下，request code
    private static final int SHARE_NO_LOGIN_REQUEST_CODE = 799;
    private BroadcastReceiver mReceiver;

    public static void launch(Context context, String url) {
        launch(context, url, null);
    }

    public static void launch(Context context, String url, String title) {
        Intent intent = new Intent(context, WebActivity.class);
        intent.putExtra("link", url);
        intent.putExtra("title", title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setBackgroundDrawableResource(R.color.transparent);
        attachSlidr();
    }

    protected void attachSlidr() {
        mSlidrInterface = Slidr.attach(this, App.getSlidrConfig());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initView() {
        setOnUpClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mShareBtn = (ImageButton) findViewById(R.id.iv_action);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        initWebView();
    }

    private void initWebView() {
        mWebView = (WebView) findViewById(R.id.webview);//new QsbkWebView(this, mPluginClassMap);
        mWebView.setInitialScale(1);
        mWebView.setVerticalScrollBarEnabled(true);
        mWebView.requestFocusFromTouch();
        mWebView.addJavascriptInterface(new JSAndroid(),"Android");

        // Enable JavaScript
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setTextZoom(100);
        settings.setBuiltInZoomControls(true);

        // Set the nav dump for HTC 2.x devices (disabling for ICS, deprecated entirely for Jellybean 4.2)
        try {
            Method gingerbread_getMethod = WebSettings.class.getMethod("setNavDump", new Class[]{boolean.class});

            String manufacturer = Build.MANUFACTURER;
            Log.d(TAG, "CordovaWebView is running on device made by: " + manufacturer);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB &&
                    Build.MANUFACTURER.contains("HTC")) {
                gingerbread_getMethod.invoke(settings, true);
            }
        } catch (NoSuchMethodException e) {
            Log.d(TAG, "We are on a modern version of Android, we will deprecate HTC 2.3 devices in 2.8");
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "Doing the NavDump failed with bad arguments");
        } catch (IllegalAccessException e) {
            Log.d(TAG, "This should never happen: IllegalAccessException means this isn't Android anymore");
        } catch (InvocationTargetException e) {
            Log.d(TAG, "This should never happen: InvocationTargetException means this isn't Android anymore.");
        }

        //We don't save any form data in the application
        settings.setSaveFormData(false);
        settings.setSavePassword(false);

        // Jellybean rightfully tried to lock this down. Too bad they didn't give us a whitelist
        // while we do this
        // 允许跨域访问
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
            settings.setAllowUniversalAccessFromFileURLs(true);
        // Enable database
        // We keep this disabled because we use or shim to get around DOM_EXCEPTION_ERROR_16
        String databasePath = getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setDatabaseEnabled(true);
        settings.setDatabasePath(databasePath);

        settings.setGeolocationDatabasePath(databasePath);

        // Enable DOM storage
        settings.setDomStorageEnabled(true);

        // Enable built-in geolocation
        settings.setGeolocationEnabled(true);

        // Enable AppCache
        // Fix for CB-2282
        settings.setAppCacheMaxSize(5 * 1048576);
        String pathToCache = getActivity().getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(pathToCache);
        settings.setAppCacheEnabled(true);

        // Fix for CB-1405
        // Google issue 4641
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + " " + getCustomUserAgent());

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    mWebView.getSettings().getUserAgentString();
                }
            };
            registerReceiver(mReceiver, intentFilter);
        }
        // end CB-1405
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            //setLayerType(LAYER_TYPE_SOFTWARE, null);
        }

        // Android webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，需要设置开启。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        if (App.getInstance().isDebug()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        generalEnableCrossDomain();

        mWebView.setWebChromeClient(new WebChromeClient() {

            /**
             * Tell the host application the current progress of loading a page.
             *
             * @param view        The WebView that initiated the callback.
             * @param progress Current page loading progress, represented by
             */
            @Override
            public void onProgressChanged(WebView view, int progress) {
                if (progressBar != null) {
                    if (progress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
                        progressBar.setVisibility(ProgressBar.VISIBLE);
                        if (mSlidrInterface != null) {
                            mSlidrInterface.lock();
                        }
                    }
                    progressBar.setProgress(progress);
                    if (progress == 100) {
                        progressBar.setVisibility(ProgressBar.GONE);
                        if (mSlidrInterface != null) {
                            mSlidrInterface.unlock();
                        }
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                setTitle(title);
            }
        });
    }

    public String getCustomUserAgent() {
        String userAgent = "default";
        String packageName = getActivity().getPackageName();
        if (packageName != null) {
            userAgent = packageName.replace("com.", "");
        }
        userAgent = userAgent + "/" + AppUtils.getAppVersionName() + "." + AppUtils.getAppVersionCode();
        return userAgent;
    }

    @SuppressLint("NewApi")
    public void generalEnableCrossDomain() {
        WebSettings websettings = mWebView.getSettings();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {

            enablecrossdomain41();
            websettings.setAllowUniversalAccessFromFileURLs(true);
            websettings.setAllowFileAccessFromFileURLs(true);

        } else {
            enableCrossDomain();
        }

    }

    public void enableCrossDomain() {
        try {
            Field field = WebView.class.getDeclaredField("mWebViewCore");
            field.setAccessible(true);
            Object webviewcore = field.get(this);
            Method method = webviewcore.getClass().getDeclaredMethod("nativeRegisterURLSchemeAsLocal", String.class);
            method.setAccessible(true);
            method.invoke(webviewcore, "http");
            method.invoke(webviewcore, "https");
        } catch (Exception e) {
            Log.d("wokao", "enablecrossdomain error");
            e.printStackTrace();
        }
    }

    public void enablecrossdomain41() {
        try {
            Field webviewclassic_field = WebView.class.getDeclaredField("mProvider");
            webviewclassic_field.setAccessible(true);
            Object webviewclassic = webviewclassic_field.get(this);
            Field webviewcore_field = webviewclassic.getClass().getDeclaredField("mWebViewCore");
            webviewcore_field.setAccessible(true);
            Object mWebViewCore = webviewcore_field.get(webviewclassic);
            Field nativeclass_field = webviewclassic.getClass().getDeclaredField("mNativeClass");
            nativeclass_field.setAccessible(true);
            Object mNativeClass = nativeclass_field.get(webviewclassic);

            Method method = mWebViewCore.getClass().getDeclaredMethod("nativeRegisterURLSchemeAsLocal", new Class[]{int.class, String.class});
            method.setAccessible(true);
            method.invoke(mWebViewCore, mNativeClass, "http");
            method.invoke(mWebViewCore, mNativeClass, "https");
        } catch (Exception e) {
            Log.d("wokao", "enablecrossdomain error");
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent != null) {
            link = intent.getStringExtra("link");
            title = intent.getStringExtra("title");
        }

        if (!TextUtils.isEmpty(title)) {
            setTitle(title);
        }

        loadUrl(link);
    }

    protected void loadUrl(String url) {
        loadUrl(url, null);
    }

    protected void loadUrl(String url, Map<String, String> header) {
        if (TextUtils.isEmpty(url)) {
            // url为空，则关闭页面
            BuglyLog.e("WebActivity", "url is empty!!!");
            finish();
            return;
        }

        // 处理内部请求URL，带上默认参数和签名参数
//        String requestUrl = NetRequest.handleRequestUrl(url);
//
//        boolean isSupportedHost = !url.equals(requestUrl);

        String requestUrl;
        if (url.contains("?")) {
            requestUrl = url + "&device=android";
        } else {
            requestUrl = url + "?device=android";
        }

        if (header == null) {
            header = new HashMap<>();
        }
        header.put("app_ver", String.valueOf(AppUtils.getAppVersionCode()));
        header.put("model", Build.FINGERPRINT);
        if (ConfigManager.getInstance().isLogin()) {// && isSupportedHost) {
            header.put("token", ConfigManager.getInstance().getToken());
            header.put("user_id", ConfigManager.getInstance().getUserId());
        }
        mWebView.loadUrl(requestUrl, header);
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            if (mWebView != null) {
                mWebView.getClass().getMethod("onPause").invoke(mWebView, (Object[]) null);
                isOnPause = true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (isOnPause) {
                if (mWebView != null) {
                    mWebView.getClass().getMethod("onResume").invoke(mWebView, (Object[]) null);
                }
                isOnPause = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        // 每次退出页面去除cookie
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.removeAllCookies(null);
        } else {
            cookieManager.removeAllCookie();
        }
        if (null != mReceiver) {
            //fix https://bugly.qq.com/v2/crash-reporting/errors/0fb431a2aedd4952a86c0582f31a18da/622050?pid=1
            try {
                unregisterReceiver(mReceiver);
            } catch (Throwable throwable) {
            }
            mReceiver = null;
        }
        super.onDestroy();
    }


    public boolean onKeyDown(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_BACK && null != mWebView && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return false;
    }

    public void reloadUrl() {
        loadUrl(link);
    }

    public void reloadUrl(String url) {
        loadUrl(url);
    }

    public String getUrl() {
        return link;
    }

    @Override
    public void onBackPressed() {
        if (!mActivityFinishFlag && mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            finish();
        }
    }
}
